package com.itjeffrey.autocode.service.impl;

import com.itjeffrey.autocode.bo.RandomWordBO;
import com.itjeffrey.autocode.service.AsyncService;
import com.itjeffrey.autocode.util.ACBaseUtil;
import com.itjeffrey.autocode.util.SpringContextHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.Set;

/**
 * 异步处理服务实现类
 * @From: Jeffrey
 * @Date: 2021/6/5
 */
@Service
@Slf4j
public class AsynServiceImpl implements AsyncService {

    @Override
    public void generateWord() {
        new Thread(() -> {
            Set<String> set = new HashSet<>();
            for (int i = 0; i < 50; i++) {
                String randomWord;
                try {
                    //randomWord = RandomWordGenerator.getRandomWord(); // TODO 暂时忽略调用此方法避免超时异常
                    randomWord = ACBaseUtil.getWords(1, 10)[0]; //默认生成一个
                } catch (Exception e) {
                    log.warn("Generate Random Words Connect Timeout!");
                    continue;
                }
                set.add(randomWord);
            }
            //发布通知
            SpringContextHolder.publish(new RandomWordBO(this, set));
        }).start();
    }

    @Override
    @Async("asyncThreadPoolExecutor")
    public void asyncExecute() {
        log.info("Start async thread execute...");
        //test complicated task
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
        }
        log.info("End async thread execute!");
    }
}
